from django.shortcuts import render
# Create your views here.
from rest_framework import mixins, viewsets, serializers, status
from rest_framework.permissions import IsAuthenticated, BasePermission
from rest_framework.response import Response

from news.utils import StandardResultsSetPagination
from rider.models import Rider
from station.filters import OrdersFilter
from trade.models import Orders, ExpressInfo
from trade.serializers import OrdersSerializer, RiderOrdersSerializer, RobOrdersSerializer, \
    UsersOrdersFindSerializer, RobOrdersDetailsSerializer, RiderRobOrdersSerializer, ExpressInfoSerializer, \
    FindExpressInfoSerializer


# 骑手才能抢单权限
class RiderPermissionClass(BasePermission):
    def has_permission(self, request, view):
        if request.user.role_type == 2:
            return True
        return False


class OrdersView(mixins.CreateModelMixin,
                 viewsets.GenericViewSet):
    """
        create:
            用户发布订单
    """
    queryset = Orders.objects.all()
    serializer_class = OrdersSerializer

    def get_queryset(self):
        return Orders.objects.filter(users=self.request.user)

    def perform_create(self, serializer):
        orders = serializer.save()
        orders.pay_status = "taking"
        orders.save()


class UsersOrdersFindView(mixins.RetrieveModelMixin,
                          mixins.ListModelMixin,
                          mixins.DestroyModelMixin,
                          viewsets.GenericViewSet):
    """
        list:
            用户订单列表
        retrieve:
            用户订单详情
        destroy:
            用户取消订单
    """
    queryset = Orders.objects.all()
    serializer_class = UsersOrdersFindSerializer
    pagination_class = StandardResultsSetPagination
    filter_fields = ('pay_status',)
    search_fields = []

    def get_queryset(self):
        return Orders.objects.filter(users=self.request.user).order_by('-id')

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.pay_status == 'taking':
            self.perform_destroy(instance)
            return Response({"msg": "该订单已删除", "status_code": 204}, status=status.HTTP_204_NO_CONTENT)
        else:
            return Response({"err_msg": "接单不能删除", "status_code": 400}, status=status.HTTP_400_BAD_REQUEST)


class RiderOrdersView(mixins.ListModelMixin,
                      mixins.UpdateModelMixin,
                      mixins.RetrieveModelMixin,
                      mixins.DestroyModelMixin,
                      viewsets.GenericViewSet):
    """
        list:
            骑手管理订单列表
        retrieve:
            骑手管理订单详情
        update:
            骑手管理确认完成订单
        destroy:
            骑手管理取消订单
    """
    permission_classes = (IsAuthenticated, RiderPermissionClass, )
    queryset = Orders.objects.all()
    serializer_class = RiderOrdersSerializer
    pagination_class = StandardResultsSetPagination
    filter_fields = ('pay_status',)

    def get_queryset(self):
        rider = Rider.objects.filter(users=self.request.user)[0]
        return Orders.objects.filter(rider=rider)

    def perform_update(self, serializer):
        rider = Rider.objects.filter(users=self.request.user)[0]
        serializer.validated_data['rider'] = rider
        serializer.instance.pay_status = 'TRADE_FINISHED'
        orders = serializer.save()
        express_info = ExpressInfo.objects.filter(orders=orders)[0]
        express_info.express_status = 'finished'
        express_info.save()
        return orders

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"msg": "该订单已消", "status_code": 204}, status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.pay_status = 'taking'
        instance.rider = None
        instance.save()


class RobRiderOrdersView(mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         mixins.UpdateModelMixin,
                         viewsets.GenericViewSet):
    """
        list:
            骑手抢单列表
        retrieve:
            骑手抢单详情
        update:
            骑手抢单
    """
    permission_classes = (IsAuthenticated, RiderPermissionClass, )
    queryset = Orders.objects.all()
    serializer_class = RobOrdersSerializer
    pagination_class = StandardResultsSetPagination
    # filter_fields = ('station__address',)
    # search_fields = ['station__address']
    filterset_class = OrdersFilter

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return RobOrdersDetailsSerializer
        elif self.action == 'update':
            return RiderRobOrdersSerializer
        else:
            return RobOrdersSerializer

    def get_queryset(self):
        return Orders.objects.filter(pay_status='taking').order_by("-order_mount")

    def generate_express_no(self):
        # 生成快递单号
        # 当前时间+随机数
        from random import Random
        import time
        random_ins = Random()
        express_no = "{time_str}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                       ranstr=random_ins.randint(10, 99))
        return express_no

    def perform_update(self, serializer):
        rider = Rider.objects.filter(users=self.request.user)[0]
        serializer.validated_data['rider'] = rider
        serializer.instance.pay_status = 'going'
        orders = serializer.save()
        express_info = ExpressInfo()
        express_info.orders = orders
        express_info.express_no = self.generate_express_no()
        express_info.save()
        return orders


class ExpressInfoView(mixins.ListModelMixin,
                      viewsets.GenericViewSet):
    """
        list:
            快递信息查询
    """
    permission_classes = ()
    authentication_classes = ()
    queryset = ExpressInfo.objects.all()
    serializer_class = FindExpressInfoSerializer
    filter_fields = ('express_no',)
